package com.xgk.boot.module.core.job;

import com.xgk.boot.framework.common.enums.UserTypeEnum;
import com.xgk.boot.module.core.service.mail.MailSendService;
import io.micrometer.core.instrument.Gauge;
import io.micrometer.core.instrument.MeterRegistry;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

@Slf4j
@Component
public class ThreadPoolMetricsMonitor {

    private final MeterRegistry meterRegistry;

    private final MailSendService mailSendService;

    private boolean alerted = false;

    public ThreadPoolMetricsMonitor(MeterRegistry meterRegistry, MailSendService mailSendService) {
        this.meterRegistry = meterRegistry;
        this.mailSendService = mailSendService;
    }

    @Scheduled(fixedDelay = 5000)
    public void monitorThreadPoolMetrics() {
        Gauge queueSizeGauge = meterRegistry.find("executor.queued")
                .tags("name", "eventTaskExecutor").gauge();

        Gauge queueCapacityGauge = meterRegistry.find("executor.queue.remaining")
                .tags("name", "eventTaskExecutor").gauge();

        if (queueSizeGauge != null && queueCapacityGauge !=null) {

            double used = queueSizeGauge.value();
            double remaining = queueCapacityGauge.value();
            double total = used + remaining;

            double ratio = used / total;

            log.debug("线程池队列使用: {}/{} ({})", (int) used, (int) total, String.format("%.0f%%", ratio * 100));

            if (ratio > 0.5) {
                log.warn("线程池队列使用超过 50%");
                if (!alerted) {
                    alerted = true;
                    sendAlert(ratio, used, total);
                }
            } else {
                alerted = false;
            }
        } else {
            log.warn("未找到线程池 queue.size 或 queue.remaining 指标");
        }
    }

    private void sendAlert(double ratio, double used, double total) {
        String content = String.format("线程池排队率超过阈值：当前 %d / %d (%.0f%%)",
                (int) used, (int) total, ratio * 100);
        log.warn("线程池告警：{}", content);
        //TODO:对相关管理人员发送告警邮件
        String mail = "byf789byf@163.com";
        Long userId = 0L;
        Integer userType = UserTypeEnum.ADMIN.getValue();
        String templateCode = "system_alter";
        Map<String, Object> templateParams = new HashMap<>();
        templateParams.put("msg", content);
        mailSendService.sendSingleMail(mail, userId, userType, templateCode, templateParams);
    }
}

